import type { FormProps } from 'antd';
import { Button, Col, Form, Input, Row, message, Tooltip, Dropdown } from 'antd';
import style from './style.module.scss'
import { useNavigate } from 'react-router-dom';
import { logins } from '../../api/info';
import { useState, useRef, useEffect } from 'react';
import { LockOutlined, UserOutlined, EyeOutlined, EyeInvisibleOutlined, SafetyOutlined, ReloadOutlined, GlobalOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import type { MenuProps } from 'antd';

function Index() {
    const [captcha, setCaptcha] = useState<string>('')
    const [captchaInput, setCaptchaInput] = useState<string>('')
    const [passwordVisible, setPasswordVisible] = useState(false)
    const [loading, setLoading] = useState(false)
    const [captchaLoading, setCaptchaLoading] = useState(false)
    const [formData, setFormData] = useState({ username: '', password: '', captcha: '' })
    const canvasRef = useRef<HTMLCanvasElement>(null)
    const nav = useNavigate()
    
    type FieldType = {
        username?: string;
        password?: string;
        captcha?: string;
    }

    const { t, i18n } = useTranslation();

    // 获取当前语言显示文本
    const getCurrentLanguageText = () => {
        switch (i18n.language) {
            case 'zh':
                return '🇨🇳 中文';
            case 'en':
                return '🇺🇸 English';
            case 'ko':
                return '🇰🇷 한국어';
            default:
                return '🇨🇳 中文';
        }
    };

    // 语言切换菜单
    const languageItems: MenuProps['items'] = [
        {
            key: 'zh',
            label: '中文',
            icon: '🇨🇳',
            onClick: () => {
                i18n.changeLanguage('zh');
                localStorage.setItem('language', 'zh');
            }
        },
        {
            key: 'en',
            label: 'English',
            icon: '🇺🇸',
            onClick: () => {
                i18n.changeLanguage('en');
                localStorage.setItem('language', 'en');
            }
        },
        {
            key: 'ko',
            label: '한국어',
            icon: '🇰🇷',
            onClick: () => {
                i18n.changeLanguage('ko');
                localStorage.setItem('language', 'ko');
            }
        }
    ];

    // 生成随机验证码
    const generateRandomCaptcha = (): string => {
        // 使用更容易识别的字符，避免0和O、1和l等容易混淆的字符
        const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';
        let result = '';
        for (let i = 0; i < 4; i++) {
            result += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return result;
    };

    // 绘制验证码图片
    const drawCaptcha = (text: string) => {
        const canvas = canvasRef.current;
        if (!canvas) return;

        const ctx = canvas.getContext('2d');
        if (!ctx) return;

        canvas.width = 120;
        canvas.height = 40;

        // 清除画布
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // 渐变背景
        const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
        gradient.addColorStop(0, '#f8fafc');
        gradient.addColorStop(1, '#e2e8f0');
        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // 添加轻微的干扰线（减少数量，降低干扰）
        for (let i = 0; i < 2; i++) {
            ctx.strokeStyle = `rgba(59, 130, 246, ${0.1 + Math.random() * 0.1})`;
            ctx.lineWidth = 1;
            ctx.beginPath();
            ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
            ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
            ctx.stroke();
        }

        // 添加少量干扰点
        for (let i = 0; i < 15; i++) {
            ctx.fillStyle = `rgba(59, 130, 246, ${0.05 + Math.random() * 0.1})`;
            ctx.fillRect(Math.random() * canvas.width, Math.random() * canvas.height, 1, 1);
        }

        // 绘制文字
        ctx.font = 'bold 20px Arial, sans-serif';
        ctx.textBaseline = 'middle';
        
        for (let i = 0; i < text.length; i++) {
            const x = 15 + i * 22;
            const y = canvas.height / 2 + (Math.random() - 0.5) * 4;
            
            // 减少旋转角度，提高可读性
            const angle = (Math.random() - 0.5) * 0.2;
            ctx.save();
            ctx.translate(x, y);
            ctx.rotate(angle);
            
            // 使用更深的颜色，提高对比度
            const colors = ['#1e40af', '#3b82f6', '#1d4ed8', '#2563eb'];
            ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)];
            ctx.fillText(text[i], 0, 0);
            ctx.restore();
        }
    };

    // 生成验证码
    const generateCaptcha = () => {
        setCaptchaLoading(true);
        setCaptchaInput(''); // 清空输入框
        
        setTimeout(() => {
            const newCaptcha = generateRandomCaptcha();
            setCaptcha(newCaptcha);
            drawCaptcha(newCaptcha);
            setCaptchaLoading(false);
        }, 200);
    };

    // 验证验证码
    const validateCaptcha = (input: string) => {
        if (!captcha) return false;
        return input.toLowerCase() === captcha.toLowerCase();
    };

    // 处理输入变化
    const handleInputChange = (field: string, value: string) => {
        setFormData(prev => ({ ...prev, [field]: value }));
        
        // 如果是验证码输入，实时验证
        if (field === 'captcha') {
            if (value.length === 4) {
                if (validateCaptcha(value)) {
                    // 验证码正确时的视觉反馈
                    const captchaInput = document.querySelector('input[placeholder="' + t('login.inputCaptchaPlaceholder') + '"]') as HTMLInputElement;
                    if (captchaInput) {
                        captchaInput.style.borderColor = '#10b981';
                        captchaInput.style.boxShadow = '0 0 0 3px rgba(16, 185, 129, 0.1)';
                    }
                } else {
                    // 验证码错误时的视觉反馈
                    const captchaInput = document.querySelector('input[placeholder="' + t('login.inputCaptchaPlaceholder') + '"]') as HTMLInputElement;
                    if (captchaInput) {
                        captchaInput.style.borderColor = '#ef4444';
                        captchaInput.style.boxShadow = '0 0 0 3px rgba(239, 68, 68, 0.1)';
                    }
                }
            } else {
                // 重置样式
                const captchaInput = document.querySelector('input[placeholder="' + t('login.inputCaptchaPlaceholder') + '"]') as HTMLInputElement;
                if (captchaInput) {
                    captchaInput.style.borderColor = '#e5e7eb';
                    captchaInput.style.boxShadow = 'none';
                }
            }
        }
    };

    // 组件挂载时生成验证码
    useEffect(() => {
        generateCaptcha();
    }, []);

    const onFinish: FormProps<FieldType>['onFinish'] = async (values: FieldType) => {
        setLoading(true);
        
        try {
            // 验证验证码
            if (!validateCaptcha(values.captcha || '')) {
                message.error(t('login.captchaErrorMsg'));
                generateCaptcha();
                return;
            }

            const res = await logins('/login', values)
            console.log('登录响应:', res);
        const { code, data } = res.data
            
        if (code === 10000) {
            localStorage.setItem('token', data.accessToken)
            localStorage.setItem('pic', data.userInfo.avator)
            localStorage.setItem('name', data.userInfo.username)
                message.success(t('login.loginSuccess'));
            nav('/')
            } else {
                message.error(t('login.loginFail'));
                generateCaptcha();
            }
        } catch (error) {
            message.error(t('login.loginErrorMsg'));
            generateCaptcha();
        } finally {
            setLoading(false);
        }
    };

    const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
        console.log('表单验证失败:', errorInfo);
    };

    return (
        <div className={style.loginContainer}>
            {/* 语言切换按钮 */}
            <div className={style.languageSwitch}>
                <Dropdown menu={{ items: languageItems }} placement="bottomRight">
                    <Button 
                        type="text" 
                        icon={<GlobalOutlined />}
                        className={style.languageButton}
                    >
                        {getCurrentLanguageText()}
                    </Button>
                </Dropdown>
            </div>

            {/* 左侧品牌区域 */}
            <div className={style.brandSection}>
                <div className={style.brandContent}>
                    <div className={style.brandTitle}>
                        <h1>{t('login.systemTitle')}</h1>
                        <h2>{t('login.systemSubtitle')}</h2>
                    </div>
                    
                    <div className={style.mainIllustration}>
                        <div className={style.documentIcon}>
                            <div className={style.documentContent}>
                                <div className={style.checkmark}>✓</div>
                                <div className={style.cross}>✗</div>
                                <div className={style.textLines}>
                                    <div className={style.line}></div>
                                    <div className={style.line}></div>
                                    <div className={style.line}></div>
                                </div>
                            </div>
                        </div>
                        <div className={style.illustrationRing}></div>
                    </div>
                    
                    <div className={style.cloud1}></div>
                    <div className={style.cloud2}></div>
                </div>
                
                {/* 背景装饰点 */}
                <div className={style.backgroundDots}></div>
            </div>

            {/* 右侧登录表单 */}
            <div className={style.formSection}>
                <div className={style.formContainer}>
                    <h2 className={style.formTitle}>{t('login.userLogin')}</h2>
                    
                    <Form
                        name="loginForm"
                        style={{ width: '100%' }}
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                        size="large"
                >
                    <Form.Item
                        name="username"
                            rules={[{ required: true, message: t('login.inputUsername') }]}
                        >
                            <Input 
                                prefix={<UserOutlined className={style.inputIcon} />} 
                                placeholder={t('login.inputAccount')}
                                className={style.customInput}
                                onChange={(e) => handleInputChange('username', e.target.value)}
                                onPressEnter={() => {
                                    const passwordInput = document.querySelector('input[type="password"]') as HTMLInputElement;
                                    passwordInput?.focus();
                                }}
                            />
                    </Form.Item>
                        
                    <Form.Item
                        name="password"
                            rules={[{ required: true, message: t('login.inputPassword') }]}
                        >
                            <Input 
                                prefix={<LockOutlined className={style.inputIcon} />}
                                suffix={
                                    <Tooltip title={passwordVisible ? t('login.hidePassword') : t('login.showPassword')}>
                                        {passwordVisible ? (
                                            <EyeInvisibleOutlined 
                                                className={style.passwordToggle}
                                                onClick={() => setPasswordVisible(false)}
                                            />
                                        ) : (
                                            <EyeOutlined 
                                                className={style.passwordToggle}
                                                onClick={() => setPasswordVisible(true)}
                                            />
                                        )}
                                    </Tooltip>
                                }
                                type={passwordVisible ? 'text' : 'password'}
                                placeholder={t('login.inputPasswordPlaceholder')}
                                className={style.customInput}
                                onChange={(e) => handleInputChange('password', e.target.value)}
                                onPressEnter={() => {
                                    const captchaInput = document.querySelector('input[placeholder="' + t('login.inputCaptchaPlaceholder') + '"]') as HTMLInputElement;
                                    captchaInput?.focus();
                                }}
                            />
                    </Form.Item>
                        
                    <Form.Item
                            name="captcha"
                            rules={[{ required: true, message: t('login.inputCaptcha') }]}
                            extra={
                                <div style={{
                                    fontSize: '12px',
                                    color: '#6b7280',
                                    marginTop: '4px',
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '4px'
                                }}>
                                    <span>💡</span>
                                    <span>{t('login.captchaTip')}</span>
                                </div>
                            }
                        >
                            <Row gutter={12}>
                                <Col span={14}>
                                    <Input 
                                        prefix={<SafetyOutlined className={style.inputIcon} />}
                                        placeholder={t('login.inputCaptchaPlaceholder')}
                                        value={captchaInput}
                                        onChange={(e) => {
                                            setCaptchaInput(e.target.value);
                                            handleInputChange('captcha', e.target.value);
                                        }}
                                        className={style.customInput}
                                        onPressEnter={() => {
                                            const form = document.querySelector('form') as HTMLFormElement;
                                            form?.requestSubmit();
                                        }}
                                        maxLength={4}
                                    />
                            </Col>
                                <Col span={10}>
                                    <div className={style.captchaContainer}>
                                        <canvas 
                                            ref={canvasRef}
                                            className={style.captchaCanvas}
                                            onClick={generateCaptcha}
                                            title={t('login.clickToRefresh')}
                                        />
                                        <Button 
                                            type="text"
                                            icon={<ReloadOutlined spin={captchaLoading} />}
                                            onClick={generateCaptcha}
                                            className={style.refreshButton}
                                            title={t('login.refreshCaptcha')}
                                        />
                                    </div>
                            </Col>
                        </Row>
                    </Form.Item>

                        <Form.Item>
                            <Button 
                                type="primary" 
                                htmlType="submit" 
                                loading={loading}
                                className={style.loginButton}
                            >
                                {loading ? t('login.loginLoading') : t('login.login')}
                        </Button>
                        </Form.Item>
                </Form>
                    
                    <div className={style.registerLink}>
                        {t('login.noAccount')} 
                        <a onClick={() => nav('/register')} className={style.linkText}>
                            {t('login.goToRegister')}
                        </a>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default Index
